

import Cookie from 'js-cookie';
// 一维数组变成树
export function treeData(data, code, pCode, fistrValue = null) {
    let cloneData = JSON.parse(JSON.stringify(data))
    let resultData = cloneData.filter(pItem => {
        let childArr = cloneData.filter(childItem => pItem[code] == childItem[pCode])
        childArr.length > 0 ? pItem['children'] = childArr : ''
        return pItem[pCode] == fistrValue
    })
    return resultData
}

// 把树转成一维数组
export function singleArr(data, child = 'children') {
    let newList = []
    const treeFun = (data) => {
        data.forEach(item => {
            newList.push(item)
            if (item[child] && item[child].length > 0) {
                treeFun(item[child])
            }
        })
    }
    treeFun(data)
    return newList
}

// 去重 val // 对比字段
export function unique(list, val) {
    let obj = {}
    let result = []
    // 去掉重复的
    list.forEach(item => {
        if (!obj[item[val]]) {
            result.push(item)
            obj[item[val]] = true
        }
    })
    return result
}
// 将list转为树
export function formatListToTree(list, idField = 'id', pidField = 'parentId') {
    let idMap = {}

    list.forEach(item => {
        let idValue = item[pidField] || '0';
        let listByList = idMap[idValue] || [];
        listByList.push(item)
        idMap[idValue] = listByList;
    })

    function parentFindChildren(idValue, idMap) {
        let list = idMap[idValue] || false;
        if (list) {
            list.forEach(item => {
                item.children = parentFindChildren(item[idField], idMap)
                item.leaf = !item.children
            })
        }
        return list;
    }

    return parentFindChildren('0', idMap)
}

// 处理状态值回显
export function statusText(list, val, backLabel = 'label', value = 'value') {
    let text = ''
    try {
        text = list.find(item => item[value] == val)[backLabel]
    } catch (error) {

    }
    return text
}
// 将图片转为base64
export function getImgToBase64(url, callback) {
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL('image/png');
        callback(dataURL);
        canvas = null;
    };
    img.src = url;
}

// 将base64转为File
export function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

// 上下五年年份计算
export function yearFun(n = 6) {
    let addArr = []
    let subArr = []
    let y = new Date().getFullYear()
    for (let i = 1; i < n; i++) {
        let addValue = y + (n - i)
        let subValue = y - i
        addArr.push({ label: addValue, value: addValue })
        subArr.push({ label: subValue, value: subValue })
    }
    let yearsArr = [...addArr, { label: y, value: y }, ...subArr]

    return yearsArr

}
// 打开表单详情
export function openFormDetail(params) {

    console.log('获取token', Cookie.get('token'))

    let url = `${import.meta.env.VITE_APP_CLIENT_HTTPS_URL}/#/examine/detailPage?flowEngineInstanceId=${params.flowId}&token=${Cookie.get('token')}&isThird=y`
    window.open(url, '_blank')
}
function getDecimalLength(arg = '') {
    try {
        return arg.toString().split(".")[1].length
    } catch (e) {
        return 0
    }
}
function getNum(arg = '') {
    return Number(arg.toString().replace(".", ""))
}

export function keepDecimals(val, places, type) {
    if (typeof type === 'undefined') type = 1;
    var num = val + '';
    var numStart = num.split('.')[0];
    var numEnd = num.split('.')[1];
    var powVal = Math.pow(10, places);
    if (numEnd) {
        num = Math.round(num * powVal) / powVal + ''
        if (num.split('.')[1] && num.split('.')[1].length < places) {
            for (var n = 0; n < places - num.split('.')[1].length; n++) {
                num += '0'
            }
        }
    } else {
        num = numStart + '.'
        for (var n = 0; n < places; n++) {
            num += '0'
        }
    }
    return type == 1 ? num = num * 1 : num = num + ''
}

// 加减乘除运算
/**
 * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
 *
//  * @param num1加数1 | num2加数2
 */
export function numAdd(arg1, arg2) {
    var me = this;
    if (typeof arg1 === 'string') {
        arg1 = Number(arg1);
    }
    if (typeof arg2 === 'string') {
        arg2 = Number(arg2);
    }
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return keepDecimals((arg1 * m + arg2 * m) / m, 2);
};
export function numAddNoKeep(arg1, arg2) {
    let r1, r2, m
    try { r1 = arg1.toString().split('.')[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split('.')[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return (numMulti(arg1, m) + numMulti(arg2, m)) / m
};
/**
* 加法运算，避免数据相减小数点后产生多位数和计算精度损失。
*
//  * @param num1被减数 | num2减数
*/
export function numSub(num1, num2) {
    var baseNum, baseNum1, baseNum2;
    var precision; // 精度
    try {
        baseNum1 = num1.toString().split(".")[1].length;
    } catch (e) {
        baseNum1 = 0;
    }
    try {
        baseNum2 = num2.toString().split(".")[1].length;
    } catch (e) {
        baseNum2 = 0;
    }
    baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
    precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
    return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
};
/**
* 乘法运算，避免数据相乘小数点后产生多位数和计算精度损失。
*
*/
export function numMulti(num1, num2) {
    var baseNum = 0;
    try {
        baseNum += num1.toString().split(".")[1].length;
    } catch (e) { }
    try {
        baseNum += num2.toString().split(".")[1].length;
    } catch (e) { }
    return keepDecimals(Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum), 2);
};

export function numCheck(val) {
    val = val.toString()
    const t = val.charAt(0)
    // 转化为数字形式--包含小数，负数
    // 先把非数字的都替换掉，除了数字和.
    val = val.replace(/[^\d.]/g, '')
    // 必须保证第一个为数字而不是.
    val = val.replace(/^\./g, '')
    // 保证只有出现一个.而没有多个.
    val = val.replace(/\.{2,}/g, '.')
    // 保证.只出现一次，而不能出现两次以上
    val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    // 如果第一位是负号，则允许添加
    if (t === '-') {
        val = '-' + val
    }
    return val * 1
}
export function accDiv(arg1, arg2) {
    let t1, t2;
    t1 = getDecimalLength(arg1)
    t2 = getDecimalLength(arg2)
    if (t1 - t2 > 0) {
        return (getNum(arg1) / getNum(arg2)) / Math.pow(10, t1 - t2)
    } else {
        return (getNum(arg1) / getNum(arg2)) * Math.pow(10, t2 - t1)
    }
}